﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

using GroupCheer.Common;
namespace GroupCheer
{
    public partial class doUpdate : System.Web.UI.Page
    {
        oAuthFacebookApi oAuth=null;
        private string currentMsg = "";
       // public KinteraSessionState session = new KinteraSessionState();

        private string groupId = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            string url = "";
            oAuth = oAuthFacebookApi.Instance;
            if (Request["code"] == null)
            {
                //Redirect the user back to Facebook for authorization. 
                Response.Redirect(oAuth.AuthorizationLinkGet());
            }
            else
            {
                try
                {
                    //Get the access token and secret. 
                    oAuth.AccessTokenGet(Request["code"]);

                    if (oAuth.Token.Length > 0)
                    {
                        //We now have the credentials, so we can start making API calls 
                        //url = "https://graph.facebook.com/me/feed?limit=1&access_token=" + oAuth.Token;
                        //var json = oAuth.WebRequest(oAuthFacebookApi.Method.GET, url, String.Empty);

                        //JavaScriptSerializer sr = new JavaScriptSerializer();
                        //FacebookFeedsWithAccessToken feed = sr.Deserialize<FacebookFeedsWithAccessToken>(json);
                        //foreach (FacebookFeedWithAccessToken item in feed.data)
                        //{
                        //    //167431
                        //    //this.lblLastUpdate.Text = item.message;
                        //    currentMsg = item.message;
                        //}

                        //if (!IsPostBack)
                        //{
                        //    //txtCaption.Text = SetDefaultCaption();
                        //    //txtLink.Text = SetDefaultLink();
                        //}
                        //this.imgCurrentUser.ImageUrl = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/48628_100001423220115_6011_q.jpg";
                        init();
                        //GetGruop();
                        //oAuth.SearchGroup("Group by Zaric");
                    }
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    failed();
                }
            }
        }

        private void GetGruop()
        {
            if (oAuth.Token.Length > 0)
            {
                //We now have the credentials, so we can start making API calls 
                //get the group id of Group by Zaric(256627431097033)
                string url = "https://graph.facebook.com/me/groups?limit=1&access_token=" + oAuth.Token;
                var json = oAuth.WebRequest(oAuthFacebookApi.Method.GET, url, String.Empty);
                //use the id get the group information
                url = "https://graph.facebook.com/256627431097033/feed?access_token=" + oAuth.Token;
                json = oAuth.WebRequest(oAuthFacebookApi.Method.GET, url, String.Empty);
                this.groupId = "256627431097033";
                //oAuth.UpdateGroupMessage("this is from my app", "256627431097033");
            }
        }
        private void init()
        {
            pnlError.Visible = false;
            pnlThankYou.Visible = false;
            pnlStatusForm.Visible = true;
            //lblName.Text = oAuth.GetUser().name;
        }

        private void successful()
        {
            pnlError.Visible = false;
            pnlThankYou.Visible = true;
            pnlStatusForm.Visible = false;
        }

        private void failed()
        {
            pnlError.Visible = true;
            pnlThankYou.Visible = false;
            pnlStatusForm.Visible = false;
        }

        protected void btnAgain_Click(object sender, EventArgs e)
        {
            //txtCaption.Text = SetDefaultCaption();
            //txtLink.Text = SetDefaultLink();
            lblInfo.Text = "";
            init();
        }

        private void CreateTopic()
        {
            SaveTopicToDB();
            string fbid = PostTopicToFB();
            UpdateTopicInDB(fbid);
        }

        private void SaveTopicToDB()
        {

        }

        private string  PostTopicToFB()
        {
            return "";
        }

        /// <summary>
        /// Save topic id which generated in FB and send status into our db
        /// </summary>
        private void UpdateTopicInDB(string fbid)
        {

        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string poststring = this.txtStatus.Text.Trim();
                if (LogStatus(poststring))
                {
                    if (string.IsNullOrEmpty(poststring))
                    {
                        this.lblInfo.Text = "Status must not be empty...";
                        return;
                    }

                    if (currentMsg == poststring)
                    {
                        this.lblInfo.Text = "This status update is identical to the previous one...";
                        return;
                    }
                    if (poststring.Length > 140)
                    {
                        this.lblInfo.Text = "Status must not be more than 140 characters...";
                        return;
                    }
                    string[] groupIds = oAuth.SearchGroup("Group by Zaric");

                    //set userID as the topic id, so we can post the comments
                    oAuth.UserID = groupIds[0];
                    oAuth.UserID = "256627431097033";
                    oAuth.UserID = "259213527505090";
                    //oAuth.PostWallMessage(poststring,"","","","","","");
                    oAuth.PostComments(poststring);
                    //oAuth.UpdateStatus(poststring, this.txtLink.Text.Trim(), this.txtCaption.Text.Trim());
                    successful();
                }
                else
                {
                    this.lblInfo.Text = "Sorry, there is something wrong with update, please try again...";
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                failed();
            }
            finally
            {

            }
        }

        private string SetDefaultCaption()
        {
            //167414
            return string.Format("Please join me in supporting a great cause.");
        }

        private string SetDefaultLink()
        {
            //167414
            //return string.Format("http://blba.us/i.asp?id={0}-{1}-{2}", session["FBEid"].ToString(), session["FBSid"].ToString(), "1");
            return "";
        }

        private bool LogStatus(string postString)
        {
            int inteid = 0;
            int intsid = 0;
            string msg = "";

            try
            {
                //inteid = Kintera.Util.TryParseInt32(session["FBEid"].ToString(), 0);
                //intsid = Kintera.Util.TryParseInt32(session["FBSid"].ToString(), 0);
                msg = Server.HtmlEncode(postString);
            }
            catch
            {
                return false;
            }


            if (string.IsNullOrEmpty(msg) == false)
            {
                //LogMessages.LogMessage(inteid, intsid, 1, msg);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}